/*
 * @Author: wuzhouhai wzh200x@126.com
 * @Date: 2024-03-19 19:04:11
 * @LastEditors: wuzhouhai wzh200x@126.com
 * @LastEditTime: 2024-05-17 11:16:57
 * @FilePath: \phoenix_client_sdk\PhoenixComponent.ts
 * @Description:
 */
// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

const { ccclass, property } = cc._decorator;
import PhoenixIns, { Phoenix } from './Phoenix';
import { ErrorLocalCode } from './defines/error.local.define';
import { PhoenixEventDefine } from './defines/event.define';
import { PlatformDefine } from './defines/platform.define';
import { Account } from './entities/Account';
import { Avatar } from './entities/Avatar';

@ccclass
export default class PhoenixComponent extends cc.Component {
    phoenix: Phoenix = null;
    @property({ displayName: '服务器地址', tooltip: '填写IP或是域名' })
    host = '';

    @property({ displayName: '服务器端口', tooltip: '80或443请留空' })
    port = '';

    @property({ displayName: '请求签名秘钥', tooltip: '找服务器开发获取' })
    secretKey = '';

    @property({ displayName: '是否Https' })
    isSSL: boolean = false;

    @property({ type: cc.Enum(PlatformDefine), displayName: '平台', tooltip: '请选择平台' })
    platform: number = 0;

    start() {
        this.phoenix = PhoenixIns;
        this.phoenix.init(this.platform, this.host, this.port, this.isSSL, this.secretKey);
        this.phoenix.setPhoenixComponent(this);
    }

    loginCallBack(re: boolean, reCode: number) {
        if (re) {
            this.node.emit(PhoenixEventDefine.PHOENIX_LOGIN_SUCCESS, reCode);
        } else {
            this.node.emit(PhoenixEventDefine.PHOENIX_LOGIN_FAIL, reCode);
        }
    }

    registerEvent(e: PhoenixEventDefine, callback: Function) {
        this.node.on(e, callback);
    }

    platformLogin(account, pass) {
        this.phoenix.initAccount(account, pass);
        // 第三方平台,要先去获取openid
        if (this.phoenix.isThirdPlatform()) {
            this.phoenix.thirdPlatformLogin((re) => {
                if (re == 0) {
                    this.gameStartLogin();
                } else {
                    this.loginCallBack(false, re);
                }
            });
        } else {
            this.gameStartLogin();
        }
    }

    checkLoginHasAvatar(): boolean {
        return this.phoenix.checkLoginHasAvatar();
    }

    clear() {
        this.phoenix.clear();
    }

    /**
     * 异步创建角色方法
     * @param avatarData 角色数据，泛型T，具体类型根据使用场景确定
     * @param name 角色名称，默认为空字符串
     * @returns 返回一个Promise，该Promise解析为一个数字类型，表示操作的结果代码
     */
    async createAvatar<T>(avatarData: T, name: string = ''): Promise<Number> {
        let reCode: Number = 0; // 初始化返回代码为0
        // 调用phoenix的createAvatar方法创建角色，然后打印并赋值返回代码
        await this.phoenix.createAvatar<T>(avatarData, name).then((code) => {
            console.log(code);
            reCode = code;
        });
        return reCode; // 返回操作结果代码
    }

    async getAvatar<T>(): Promise<Number> {
        let reCode: Number = 0;
        await this.phoenix.getAvatar<T>().then((code) => {
            console.log(code);
            reCode = code;
        });
        return reCode;
    }

    async updateAvatar(): Promise<Number> {
        let reCode: Number = 0;
        await this.phoenix.updateAvtar().then((code) => {
            console.log(code);
            reCode = code;
        });
        return reCode;
    }

    async updateAccountToken(): Promise<Number> {
        let reCode: Number = 0;
        await this.phoenix.updateAccountToken().then((code) => {
            console.log(code);
            reCode = code;
        });
        return reCode;
    }

    async updateThirdAccountToken(): Promise<Number> {
        let reCode: Number = 0;
        await this.phoenix.updateThirdAccountToken().then((code) => {
            console.log(code);
            reCode = code;
        });
        return reCode;
    }

    async alipayReportAction(actionCode: string, actionFinishChannel: string): Promise<Number> {
        let reCode: Number = 0;
        await this.phoenix.alipayReportAction(actionCode, actionFinishChannel).then((code) => {
            console.log(code);
            reCode = code;
        });
        return reCode;
    }

    queryServerInfo() {
        this.phoenix.queryServerInfo((code) => {
            console.log(code);
            if (code == 0) {
                this.node.emit(PhoenixEventDefine.PHONIX_QUERY_SERVER_SUCCESS, code);
            } else {
                this.node.emit(PhoenixEventDefine.PHONIX_QUERY_SERVER_FAIL, code);
            }
        });
    }

    /**
     * 去中心服务器查询账号及账号所在服务器信息
     */
    gameStartLogin() {
        let reCode: Number = 0;
        this.phoenix.queryAccount((code) => {
            console.log(code);
            reCode = code;
            if (reCode == 0) {
                this.node.emit(PhoenixEventDefine.PHONIX_QUERY_CENTER_SUCCESS, reCode);
                // 先更新选服
                this.phoenix.updateCenter((code) => {
                    if (code == 0) {
                        // 再执行登录
                        this.node.emit(PhoenixEventDefine.PHONIX_CENTER_UPDATE_SUCCESS, code);
                        this.phoenix.gameLogin();
                    } else {
                        this.node.emit(PhoenixEventDefine.PHONIX_CENTER_UPDATE_FAIL, code);
                    }
                });
            } else {
                this.node.emit(PhoenixEventDefine.PHONIX_QUERY_CENTER_FAIL, reCode);
            }
        });
    }

    async serverCallThirdPlatform(thirdUrl: string, data: object): Promise<Number> {
        let reCode: Number = 0;
        await this.phoenix.serverCallThirdPlatform(thirdUrl, data).then((code) => {
            console.log(code);
            reCode = code;
        });
        if (reCode == 0) {
            this.node.emit(PhoenixEventDefine.PHONIX_THIRD_CALL_SUCCESS, this.phoenix.getThirdCallBackData());
        } else {
            this.node.emit(PhoenixEventDefine.PHONIX_THIRD_CALL_FAIL, reCode);
        }
        return reCode;
    }

    public selectServerZone(zone: number) {
        return this.phoenix.selectServerBySid(zone);
    }

    public selectServer(index?: number) {
        return this.phoenix.selectServer(index);
    }

    public getAccountIns(): Account {
        return this.phoenix.getAccountIns();
    }

    public getAvatarIns(): Avatar<any> {
        return this.phoenix.getAvatarIns();
    }

    public getServerTimer(): number {
        return this.phoenix.getServerTimer();
    }

    public setServerTimer(serverTimer: number): void {
        this.phoenix.setServerTimer(serverTimer);
    }

    public getSelectServerZone(): number {
        return this.phoenix.getSelectServerZone();
    }
}
